package com.paradogs.gs.misc;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.reflect.GenericTypeUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.sunchenbin.mybatis.actable.manager.handler.StartUpHandler;
import com.paradogs.common.utils.SpringUtils;
import jakarta.annotation.PostConstruct;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: yumi
 * @date: 2024/10/30  14:58
 * @Description: 游戏服务基类
 */
public abstract class BaseDBService<D extends ServiceImpl<? extends BaseMapper<E>, E>, E extends BaseMgrEntity> extends BaseService {

    @Autowired
    private D dao;

    private Map<Long, E> data;

    private Class<E> dataClass;

    @Setter
    private Map<Long, Boolean> dirtyMap = new HashMap<>();

    public BaseDBService() {
        // 获得泛型的 dao 类型, By Mybatis-Plus-Tools
        Class<?>[] classes = GenericTypeUtils.resolveTypeArguments(getClass(), BaseDBService.class);
        dataClass = (Class<E>) classes[1];
    }

    /** 将数据持久化到数据库 */
    public void save2DBIfDirty() {

    }

    @PostConstruct
    private void _loadFromDB() {
        try {
            this.data = loadFromDB().stream().collect(Collectors.toMap(E::getUid, e -> e,(t, t2) -> t, LinkedHashMap::new));
        } catch (Exception err) {
            // 未创建表时先执行一次自动生成表再尝试重新获得一次
            String message = err.getCause().getMessage();
            if (message.endsWith("doesn't exist")) {
                SpringUtils.getBean(StartUpHandler.class).startHandler();
                this.data = loadFromDB().stream().collect(Collectors.toMap(E::getUid, e -> e,(t, t2) -> t, LinkedHashMap::new));
            }
        }
    }

    public List<E> loadFromDB() {
        return dao.list();
    }

}
